いつもご相談させていただきありがとうございます。golangでjsonでpostした値を取得する方法と、ある値をjson形式でoutputする方法のサンプルを作成しています。
その中で、1つのgoファイルに全てを書くのではなく、ファイルを分割したいと考えています。コンパイルした時にエラーになるので、ご教授をお願いします。
ファイル構成は以下のように作成しています。
// json_output.go
package json_output import ( "fmt" "net/http" "encoding/json" ) type Data1 struct { Title string `json:"title"` Message string `json:"message"` Status int `json:"status"` } func dumpJsonOutputHandlerFunc(w http.ResponseWriter, req *http.Request){ var data1 = Data1{} data1.Title = "sample1" data1.Message = "hello, sample1" data1.Status = 100 outputJson, err := json.Marshal(&data1) if err != nil { panic(err) } w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, string(outputJson)) }
// json_post.go
package json_post import ( "net/http" "io" "encoding/json" "fmt" "strconv" ) func Foo() { log.Print("Hello world from foo!") } func dumpJsonRequestHandlerFunc(w http.ResponseWriter, req *http.Request){ //Validate request if req.Method != "POST" { w.WriteHeader(http.StatusBadRequest) return } if req.Header.Get("Content-Type") != "application/json" { w.WriteHeader(http.StatusBadRequest) return } //To allocate slice for request body length, err := strconv.Atoi(req.Header.Get("Content-Length")) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } body := make([]byte, length) length, err = req.Body.Read(body) if err != nil && err != io.EOF { w.WriteHeader(http.StatusInternalServerError) return } var jsonBody map[string]interface{} err = json.Unmarshal(body[:length], &jsonBody) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } fmt.Printf("%v\n", jsonBody) w.WriteHeader(http.StatusOK) }
// main.go
package main import ( "net/http" ) import "./json_output" import "./json_post" func main() { json_post.Foo() http.HandleFunc("/post", json_output.dumpJsonRequestHandlerFunc()) http.HandleFunc("/json", json_post.dumpJsonOutputHandlerFunc()) http.ListenAndServe(":8080", nil) }
実行する
$ go build main.go # command-line-arguments ./main.go:11: cannot refer to unexported name json_output.dumpJsonRequestHandlerFunc ./main.go:11: undefined: json_output.dumpJsonRequestHandlerFunc ./main.go:12: cannot refer to unexported name json_post.dumpJsonOutputHandlerFunc ./main.go:12: undefined: json_post.dumpJsonOutputHandlerFunc
のようになり、うまくいきません。
こちらのサイトを参考にさせていただいて作成しました。
https://qiita.com/suin/items/f4ad02e4123c8a3c75eb
importしたものをどのようにして呼び出せば良いか、わからないので教えてください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/23 12:31