Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
# webapp-go
The sample app from Writing Web Applications on golang.org.

# Get Azure SDK package:

```sh
go get -d github.com/Azure/azure-sdk-for-go/management
```
56 changes: 48 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,64 @@
package main

import (
"bytes"
"github.com/Azure/azure-sdk-for-go/storage"
"html/template"
"io/ioutil"
"net/http"
"regexp"
"os"
"regexp"
)

var blobService storage.BlobStorageClient
var containerName = os.Getenv("AZURE_STORAGE_CONTAINER_NAME")

type Page struct {
Title string
Body []byte
}

func initAzureStorage() error {
var storageKey = os.Getenv("AZURE_STORAGE_ACCESS_KEY")
var storageName = os.Getenv("AZURE_STORAGE_ACCOUNT")
client, err := storage.NewBasicClient(storageName, storageKey)
if err != nil {
return err;
}


blobService = client.GetBlobService()
_, err = blobService.CreateContainerIfNotExists(containerName, storage.ContainerAccessTypePrivate)
if err != nil {
return err;
}

return nil;
}

func (p *Page) save() error {
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
// ignoring error since we do not care if the file doesn't exist
blobService.DeleteBlob(containerName, p.Title)
err := blobService.CreateBlockBlobFromReader(containerName, p.Title, uint64(len(p.Body)), bytes.NewReader(p.Body))
if err != nil {
return err
}

return nil
}

func loadPage(title string) (*Page, error) {
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
var body []byte
data, err := blobService.GetBlob(containerName, title)
if err == nil {
body, err = ioutil.ReadAll(data)
}

if data != nil {
data.Close()
}
return &Page{Title: title, Body: body}, nil

return &Page{Title: title, Body: body}, err
}

func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
Expand Down Expand Up @@ -81,6 +116,11 @@ func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.Handl
}

func main() {
err := initAzureStorage()
if err != nil {
panic(err)
}

http.HandleFunc("/view/", makeHandler(viewHandler))
http.HandleFunc("/edit/", makeHandler(editHandler))
http.HandleFunc("/save/", makeHandler(saveHandler))
Expand Down