Restful API

RESTfulAPI #

Status Code #

  • 200 : StatusOK
  • 201 : StatusCreated
  • 404 : StatusNotFound

method #

  • GET
  • POST

Javascript Client #

Get (JSON) #

fetch('http://192.168.10.10:8080/albums')
.then(response => response.json())
.then(json => albums = json)">

Post (JSON) #

data = {'title': title, 'artist': artist, 'price': Number(price)};
console.log(data);
fetch('http://192.168.10.10:8080/albums', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
    })

Post (File) #

Go Client (http) #

Get (JSON) #

Go Server (Gin) #

Get (JSON) #

type Album struct {
    ID     int64   `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}
func getAlbums(c *gin.Context) {
	albums, err := albumsAll()
	fmt.Printf("Albums found: %v\n", albums)

	if err == nil {
	    c.IndentedJSON(http.StatusOK, albums)
	} else {
		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
	}
}
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")
	idu64, _ := strconv.ParseInt(id, 10, 64)
	album, err := albumByID(idu64)
	if err == nil {
		c.IndentedJSON(http.StatusOK, album)
	} else {
		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
	}
}

POST (JSON) #

func postAlbums(c *gin.Context) {
    var newAlbum Album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        fmt.Fprintf(os.Stderr, "postALbums, BIndJson ERR")
        return
    }

    // Add the new album to the slice.
	addAlbum(newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

POST (File) #


func postUpload(c *gin.Context) {
    file, _ := c.FormFile("file")
    log.Println(file.Filename)

    ctx := context.Background()
    endPoint := "IPアドレス:9000"
    accessKeyID := "アクセスキー"
    secretAccessKey :="シークレットアクセスキー"
    useSSL := false

    minioClient, err := minio.New(endPoint, &minio.Options{
        Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
        Secure: useSSL,
    })
    if err != nil {
        log.Fatalln(err)
    }
    log.Printf("%#v\n", minioClient)

    bucketName := "photo"

    fp, err := file.Open()
    if err != nil {
        log.Fatalln(err)
    }

    info, err := minioClient.PutObject(ctx, bucketName,
        file.Filename,
        fp,
        file.Size,
        minio.PutObjectOptions{})

    if err != nil {
        log.Fatalln(err)
    }

    log.Printf("Uploaded %s %d\n", file.Filename, info.Size)

}

Content-Typeをmultipart/form-dataとしてPOSTする。

curl -X POST http:/IPアドレス:8080/upload -F "file=@/ファイル名" -H "Content-Type: multipart/form-data"