go-projects/sharepoint-file-uploader/main.go
2020-06-17 14:47:24 +02:00

89 lines
2.1 KiB
Go

package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"github.com/koltyakov/gosip"
"github.com/koltyakov/gosip/auth/saml"
)
type SharepointResponse struct {
Error struct {
Message struct {
Value string `json:"value"`
} `json:"message"`
} `json:"error"`
}
type SharepointClient struct {
*gosip.SPClient
}
func save(sp *gosip.SPClient, name, directory, content string, overwrite bool) error {
apiEndpoint := fmt.Sprintf("%v/_api/web/GetFolderByServerRelativeUrl('%v')/Files/add(url='%v',overwrite=%v)", sp.AuthCnfg.GetSiteURL(), directory, name, overwrite)
req, err := http.NewRequest("POST", apiEndpoint, bytes.NewBuffer([]byte(content)))
if err != nil {
return fmt.Errorf("Unable to create a request: %v\n", err)
}
req.Header.Set("Accept", "application/json;odata=verbose")
resp, err := sp.Execute(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Unable to read a response: %v\n", err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("%s", data)
}
return nil
}
func main() {
dir := flag.String("d", "Reports", "The directory on Sharepoint")
fileName := flag.String("f", "", "The file to upload")
userName := flag.String("u", "michael", "The user for Sharepoint")
overwrite := flag.Bool("overwrite", false, "Specify if existing files should be overwritten")
siteURL := flag.String("s", "https://michuit.sharepoint.com/sites/csi", "The Sharepoint site url")
flag.Parse()
if *fileName == "" {
log.Fatal("File must be specified with -f")
}
fileBytes, err := ioutil.ReadFile(*fileName)
if err != nil {
log.Fatal(err)
}
password, ok := os.LookupEnv("SP_PASSWORD")
if !ok {
log.Fatal("SP_PASSWORD environment variable must be set!")
}
auth := &saml.AuthCnfg{
SiteURL: *siteURL,
Username: *userName,
Password: password,
}
client := &gosip.SPClient{
AuthCnfg: auth,
}
err = save(client, path.Base(*fileName), *dir, string(fileBytes), *overwrite)
if err != nil {
log.Fatal(err)
}
}