Files
zeekayandHanzo Dev 1ed3377dce web: our own router; chi is gone from this codebase
modules/web/mux.go routes the 1333 routes. chi is no longer imported anywhere in
our source.

A tree over path segments, each node trying children by specificity: exact
segment, then patterned segments in registration order, then a trailing
wildcard. That ordering is the contract — "/user/settings" must beat
"/{username}" or a user named "settings" takes over the settings page — and
matching BACKTRACKS, because a segment can match here and fail deeper while the
next candidate at this level still has to be tried.

Four segment shapes, all of which this codebase actually uses:

	users             static
	{id}              whole segment          (577)
	{sha:[a-f0-9]+}   regexp-constrained     (43)
	PACKAGES{format}  parameter mid-segment  (CRAN indexes)
	*                 trailing wildcard      (131)

A plain {name} carries no regexp. It is the overwhelming majority, and it does
not need one to match a whole segment.

The tests are the point of this commit, not the code. Each case is a way a
router can be wrong that a passing build will not reveal: static beating a
param, a regexp declining and the NEXT candidate winning (/repo/zzz is not a
sha, but "repo" is a legal username), a wildcard capturing the remainder,
"/*" matching "/" itself, HEAD falling back to GET, and — the one that matters
most — a failed branch leaving NO captured parameters behind for the branch
tried next.

Three things this turned up while wiring it in:

  Mount had to strip its prefix. A sub-router mounted at "/v1" writes its
  patterns relative to it, so handing it the full path matches nothing.
  chi_middleware.GetHead was deleted rather than reimplemented: Mux.handlerFor
  already falls back from HEAD to GET, so keeping it would have been two
  implementations of one rule.
  ChiRoutePathHandler is now RoutePathHandler and sets RouteContext.RoutePath.
  It exists so a "%2f" inside a parameter routes as one segment — without it a
  branch called "feat/x" splits and matches the wrong handler.

The vendored middleware tests used chi to register two routes each; they use a
small stdlib ServeMux shim now. modules/web imports modules/binding, so those
tests cannot import web back.

github.com/go-chi/chi/v5 remains in go.mod as an INDIRECT dependency of
markbates/goth/gothic, which drives every OAuth2 login. That is goth pulling it,
not us.

Everything green; integration compile gate green.

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-27 19:20:07 -07:00

192 lines
4.8 KiB
Go

// Copyright 2026 Hanzo AI, Inc. All rights reserved.
// Copyright 2014 Martini Authors
// Copyright 2014 The Macaron Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package binding
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
var fileTestCases = []fileTestCase{
{
description: "Single file",
singleFile: &fileInfo{
fileName: "message.txt",
data: "All your binding are belong to us",
},
},
{
description: "Multiple files",
multipleFiles: []*fileInfo{
&fileInfo{
fileName: "cool-gopher-fact.txt",
data: "Did you know? https://plus.google.com/+MatthewHolt/posts/GmVfd6TPJ51",
},
&fileInfo{
fileName: "gophercon2014.txt",
data: "@bradfitz has a Go time machine: https://twitter.com/mholt6/status/459463953395875840",
},
},
},
{
description: "Single file and multiple files",
singleFile: &fileInfo{
fileName: "social media.txt",
data: "Hey, you should follow @mholt6 (Twitter) or +MatthewHolt (Google+)",
},
multipleFiles: []*fileInfo{
&fileInfo{
fileName: "thank you!",
data: "Also, thanks to all the contributors of this package!",
},
&fileInfo{
fileName: "btw...",
data: "This tool translates JSON into Go structs: http://mholt.github.io/json-to-go/",
},
},
},
}
func Test_FileUploads(t *testing.T) {
for _, testCase := range fileTestCases {
performFileTest(t, MultipartForm, testCase)
}
}
func performFileTest(t *testing.T, binder handlerFunc, testCase fileTestCase) {
httpRecorder := httptest.NewRecorder()
c := newTestRouter()
fileTestHandler := func(actual BlogPost, errs Errors) {
assertFileAsExpected(t, testCase, actual.HeaderImage, testCase.singleFile)
assert.Len(t, actual.Pictures, len(testCase.multipleFiles))
for i, expectedFile := range testCase.multipleFiles {
if i >= len(actual.Pictures) {
break
}
assertFileAsExpected(t, testCase, actual.Pictures[i], expectedFile)
}
}
c.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) {
var actual BlogPost
errs := binder(req, &actual)
fileTestHandler(actual, errs)
})
c.ServeHTTP(httpRecorder, buildRequestWithFile(testCase))
switch httpRecorder.Code {
case http.StatusNotFound:
panic("Routing is messed up in test fixture (got 404): check methods and paths")
case http.StatusInternalServerError:
panic("Something bad happened on '" + testCase.description + "'")
}
}
func assertFileAsExpected(t *testing.T, testCase fileTestCase, actual *multipart.FileHeader, expected *fileInfo) {
if expected == nil && actual == nil {
return
}
if expected != nil && actual == nil {
assert.NotNil(t, actual)
return
} else if expected == nil && actual != nil {
assert.Nil(t, actual)
return
}
assert.EqualValues(t, expected.fileName, actual.Filename)
assert.EqualValues(t, expected.data, unpackFileHeaderData(actual))
}
func buildRequestWithFile(testCase fileTestCase) *http.Request {
b := &bytes.Buffer{}
w := multipart.NewWriter(b)
if testCase.singleFile != nil {
formFileSingle, err := w.CreateFormFile("header_image", testCase.singleFile.fileName)
if err != nil {
panic("Could not create FormFile (single file): " + err.Error())
}
formFileSingle.Write([]byte(testCase.singleFile.data))
}
for _, file := range testCase.multipleFiles {
formFileMultiple, err := w.CreateFormFile("picture", file.fileName)
if err != nil {
panic("Could not create FormFile (multiple files): " + err.Error())
}
formFileMultiple.Write([]byte(file.data))
}
err := w.Close()
if err != nil {
panic("Could not close multipart writer: " + err.Error())
}
req, err := http.NewRequest("POST", testRoute, b)
if err != nil {
panic("Could not create file upload request: " + err.Error())
}
req.Header.Set("Content-Type", w.FormDataContentType())
return req
}
func unpackFileHeaderData(fh *multipart.FileHeader) string {
if fh == nil {
return ""
}
f, err := fh.Open()
if err != nil {
panic("Could not open file header:" + err.Error())
}
defer f.Close()
var fb bytes.Buffer
_, err = fb.ReadFrom(f)
if err != nil {
panic("Could not read from file header:" + err.Error())
}
return fb.String()
}
type (
fileTestCase struct {
description string
input BlogPost
singleFile *fileInfo
multipleFiles []*fileInfo
}
fileInfo struct {
fileName string
data string
}
)