3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GolangでJSONを受け取るAPIサーバーのサンプル

Posted at

サンプルコード

main.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

// 構造を宣言
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
	// POST
    http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) {
        var user User
        json.NewDecoder(r.Body).Decode(&user)

        fmt.Fprintf(w, "%s is %d years old!", user.Name, user.Age)
    })

    // GET
    http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) {
        yuta := User{
            Name:  "yuta",
            Age:       666,
        }

        json.NewEncoder(w).Encode(yuta)
    })

    http.ListenAndServe(":8080", nil)
}


PostとGet

yuta:~ $ curl -s http://localhost:8080/get
{"name":"yuta","age":666}
yuta:~ $ 
yuta:~ $ 
yuta:~ $ curl -s -XPOST -d'{"name":"tadokoro","age":24}' http://localhost:8080/post
tadokoro is 24 years old!yuta:~ $ 
yuta:~ $ 
yuta:~ $ 
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?