Skip to content

Instantly share code, notes, and snippets.

@bohdaq
Created March 15, 2020 23:00
Show Gist options
  • Save bohdaq/9bc4ec9c732806dadf13eb162b9db9cd to your computer and use it in GitHub Desktop.
Save bohdaq/9bc4ec9c732806dadf13eb162b9db9cd to your computer and use it in GitHub Desktop.
Create new file using Github API in Go language
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
user := "YOUR_USERNAME"
token := "YOUR_TOKEN"
url := "EXAMPLE:https://api.github.com/repos/WiseHands/ClusterDev/contents/config.yaml"
fmt.Println("hello world ", user, token)
data := "some data"
encoded := base64.StdEncoding.EncodeToString([]byte(data))
type Committer struct {
Name string `json:"name"`
Email string `json:"email"`
}
type RequestBody struct {
Message string `json:"message"`
Committer Committer `json:"committer"`
Content string `json:"content"`
}
committer := Committer{
Name: "Bohdan Tsap",
Email: "bohdaq@gmail.com",
}
body := RequestBody{
Message: "commit",
Committer: committer,
Content: encoded,
}
requestByte, _ := json.Marshal(body)
requestReader := bytes.NewBuffer(requestByte)
client := &http.Client{}
req, err := http.NewRequest(http.MethodPut, url, requestReader)
req.Header.Set("Authorization", "token " + token)
if err != nil {
// handle error
log.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
// handle error
log.Fatal(err)
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment