블로그 이미지

iesay

,

출처 : https://api.raritysniper.com/public/collection/cryptopunks/id/8348

 

package main

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

type User struct {
Nftid       int     `json:"nftId"`
Rank        int     `json:"rank"`
Rarityscore float64 `json:"rarityScore"`
}

func customGet() {
// Request 객체 생성
req, err := http.NewRequest("GET", "https://api.raritysniper.com/public/collection/cryptopunks/id/8348", nil)
if err != nil {
panic(err)
}

//헤더 추가
req.Header.Add("User-Agent", "Golang-test")

// Client 객체에서 Request 실행
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

// 결과 출력
bytes, _ := ioutil.ReadAll(resp.Body)
str := string(bytes) //바이트를 문자열로

var u User
json.Unmarshal([]byte(str), &u)
fmt.Printf("%+v\n", u) // {Name:gopher Age:7}

//fmt.Println(str)

}

func main() {
customGet()

}

 

 

 

 

 

 

'go' 카테고리의 다른 글

go 프로젝트 세팅  (0) 2024.02.26
JSON Transfer  (0) 2022.04.14
Web Handler  (0) 2022.04.14
go언어 설치  (0) 2022.04.14
routing module  (0) 2022.04.14
블로그 이미지

iesay

,

JSON Transfer

go 2022. 4. 14. 13:56

https://github.com/tuckersGo/goWeb/blob/master/web2/main.go

 

https://www.youtube.com/watch?v=vOW0j6hd-Rg&ab_channel=TuckerProgramming

 

package main

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

type User struct {
  FirstName string
  LastName  string
  Email     string
  CreatedAt time.Time
}

type fooHandler struct{}

func (f *fooHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  user := new(User)
  err := json.NewDecoder(r.Body).Decode(user)
  if err != nil {
    w.WriteHeader(http.StatusBadRequest)
    fmt.Fprint(w, "Bad Request: ", err)
    return
  }
  user.CreatedAt = time.Now()

  data, _ := json.Marshal(user)
  w.WriteHeader(http.StatusOK)
  fmt.Fprint(w, string(data))
}

func barHandler(w http.ResponseWriter, r *http.Request) {
  name := r.URL.Query().Get("name")
  if name == "" {
    name = "World"
  }
  fmt.Fprintf(w, "Hello %s!", name)
}

func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello World")
  })

  mux.HandleFunc("/bar", barHandler)

  mux.Handle("/foo", &fooHandler{})

  http.ListenAndServe(":3000", mux)
}

 

URL에서 name값을 출력 

 

http://192.168.0.6:3000/bar?name='aaaaaa'

'go' 카테고리의 다른 글

go 프로젝트 세팅  (0) 2024.02.26
cryptopunks raritysniper json 파싱  (0) 2022.04.15
Web Handler  (0) 2022.04.14
go언어 설치  (0) 2022.04.14
routing module  (0) 2022.04.14
블로그 이미지

iesay

,