2
1

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 5 years have passed since last update.

Go Snippet: 最小限の JSON API サーバー

2
Last updated at Posted at 2021-03-02

シンプルな JSON API サーバー。
コピペ用

コード

package main

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

type Post struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Body  string `json:"body"`
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(&Post{ID: 1, Title: "hello", Body: "world"}); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
	log.Fatalln(http.ListenAndServe(":8080", nil))
}

確認

ブラウザから http://localhost:8080/ にアクセスする

{
	id: 1,
	title: "hello",
	body: "world"
}

curl -i http://localhost:8080/ でアクセスする

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 40

{"id":1,"title":"hello","body":"world"}
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?