github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/pkg/importer/dummy/dummy.go (about)

     1  /*
     2  Copyright 2013 The Camlistore Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package dummy is an example importer for development purposes.
    18  package dummy
    19  
    20  import (
    21  	"fmt"
    22  	"log"
    23  	"net/http"
    24  	"strings"
    25  
    26  	"camlistore.org/pkg/httputil"
    27  	"camlistore.org/pkg/importer"
    28  	"camlistore.org/pkg/jsonconfig"
    29  	"camlistore.org/pkg/schema"
    30  )
    31  
    32  func init() {
    33  	importer.Register("dummy", newFromConfig)
    34  }
    35  
    36  func newFromConfig(cfg jsonconfig.Obj, host *importer.Host) (importer.Importer, error) {
    37  	im := &imp{
    38  		url:       cfg.RequiredString("url"),
    39  		username:  cfg.RequiredString("username"),
    40  		authToken: cfg.RequiredString("authToken"),
    41  		host:      host,
    42  	}
    43  	if err := cfg.Validate(); err != nil {
    44  		return nil, err
    45  	}
    46  	return im, nil
    47  }
    48  
    49  type imp struct {
    50  	url       string
    51  	username  string
    52  	authToken string
    53  	host      *importer.Host
    54  }
    55  
    56  func (im *imp) CanHandleURL(url string) bool { return false }
    57  func (im *imp) ImportURL(url string) error   { panic("unused") }
    58  
    59  func (im *imp) Prefix() string {
    60  	return fmt.Sprintf("dummy:%s", im.username)
    61  }
    62  
    63  func (im *imp) Run(intr importer.Interrupt) (err error) {
    64  	log.Printf("Running dummy importer.")
    65  	defer func() {
    66  		log.Printf("Dummy importer returned: %v", err)
    67  	}()
    68  	root, err := im.host.RootObject()
    69  	if err != nil {
    70  		return err
    71  	}
    72  	fileRef, err := schema.WriteFileFromReader(im.host.Target(), "foo.txt", strings.NewReader("Some file.\n"))
    73  	if err != nil {
    74  		return err
    75  	}
    76  	obj, err := root.ChildPathObject("foo.txt")
    77  	if err != nil {
    78  		return err
    79  	}
    80  	return obj.SetAttr("camliContent", fileRef.String())
    81  }
    82  
    83  func (im *imp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    84  	httputil.BadRequestError(w, "Unexpected path: %s", r.URL.Path)
    85  }