DICOMweb server
How to serve an archive over HTTP with
dicomweb.Server,
or with qrscp -web. The server answers QIDO-RS, WADO-RS and STOW-RS over a
Backend, and *dcmstore.Store is one.
Overview
Server is an http.Handler. It reads requests, picks the response form,
and leaves storing and matching to the Backend. One archive can then answer
a DIMSE peer and an HTTP client alike.
Warning
Server does no authentication. Whatever wraps it decides who gets in.
Do not mount it bare on an address other machines can reach.
Serving a dcmstore archive
store, err := dcmstore.Open(dir)
if err != nil {
return err
}
mux := http.NewServeMux()
mux.Handle("/dicom-web/", http.StripPrefix("/dicom-web",
requireToken("s3cret", dicomweb.NewServer(store, dicomweb.WithMaxStoreBytes(1<<30)))))
l, err := net.Listen("tcp", "127.0.0.1:41090")
if err != nil {
return err
}
srv := &http.Server{Handler: mux}
go srv.Serve(l)
defer srv.Close()The paths are relative to where the handler is mounted, so the service at
/dicom-web goes through http.StripPrefix. The token check is a plain
wrapper:
// requireToken refuses a request without the bearer token.
func requireToken(token string, next http.Handler) http.Handler {
want := []byte("Bearer " + token)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), want) != 1 {
w.Header().Set("WWW-Authenticate", `Bearer realm="dicomweb"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}A client with the token stored and searched. A client without it got
answered 401 Unauthorized: unauthorized.
| Option | Effect |
|---|---|
WithMaxStoreBytes(n) | Bounds the body of one STOW request. Past it the server answers 413. Default 4 GiB (DefaultMaxStoreBytes). |
WithFrameEncoding(e) | How much a frame encoded on request into a lossy syntax may lose. Default DefaultFrameEncoding: JPEG quality 90, JPEG‑LS NEAR 2, JPEG 2000 at 10:1. |
A Server holds no state of its own. It is safe for use by several
goroutines when its Backend is. Every response carries
X-Content-Type-Options: nosniff.
Routes
| Method and path | Service | Answers |
|---|---|---|
GET /studies, /series, /instances | QIDO‑RS | DICOM JSON; 204 when nothing matches |
GET /studies/{study}/series, .../series/{series}/instances, /studies/{study}/instances | QIDO‑RS | the same, within a study or series |
GET /studies/{study}[/series/{series}[/instances/{instance}]] | WADO‑RS | multipart/related; type="application/dicom" |
GET any of those with /metadata | WADO‑RS | DICOM JSON, with a BulkDataURI for each value left out |
GET .../instances/{instance}/frames/{list} | WADO‑RS | one part per frame |
GET .../instances/{instance}/bulkdata/{tag} | WADO‑RS | one value, application/octet-stream |
GET a study, series or instance with /bulkdata | WADO‑RS | every bulk value, one part each |
GET an instance or its frames with /rendered or /thumbnail | WADO‑RS | image/jpeg (default) or image/png |
GET /studies/{study}/thumbnail, .../series/{series}/thumbnail | WADO‑RS | the first image's first frame |
POST /studies, POST /studies/{study} | STOW‑RS | 200 all kept, 202 some, 409 none |
These are real answers from qrscp -web, using curl on one instance's
resources:
| Request | Status |
|---|---|
.../frames/1 | 200 multipart/related; type="application/octet-stream" |
.../frames/1, Accept: multipart/related; type="image/jpeg" | 200, the frame encoded on request |
.../frames/2 (a one-frame image) | 404 |
.../frames/x | 400 |
.../rendered, .../thumbnail | 200 image/jpeg |
.../rendered, Accept: image/gif | 406 |
/studies/{study}/rendered | 501 |
.../bulkdata/7FE00010 | 200 multipart/related; type="application/octet-stream" |
/studies/{study}/bulkdata | 200 |
DELETE /studies/{study} | 405 with Allow |
/studies?PatientName=Nobody | 204 |
A refused request gets a status and a short reason in the body. The reason describes the request, never the archive's files.
Transfer syntaxes
The server picks each instance's form from the request's Accept header or
its accept parameter:
| The request asks for | The instance is sent |
|---|---|
transfer-syntax=*, anything, or nothing | as stored, byte for byte |
type="application/dicom" with no syntax | Explicit VR Little Endian, decoded if needed |
| the stored syntax | as stored |
| a native syntax, or a lossless one this library encodes | transcoded losslessly |
| a lossy syntax it is not already in | refused, 406 |
A lossy copy is a new instance, which needs a new SOP Instance UID. A retrieve does not assign one. A study request leaves out each instance that cannot be sent: 206 if some are sent, 406 if none are.
Note
Frames work differently. A frame asked for in a lossy type, such as
image/jpeg with the JPEG Baseline syntax, is encoded at the server's
FrameEncoding. A type named without a syntax gets its lossless default.
Pixels already held lossy are never encoded again.
A handler of your own can use the same rules. ChooseInstances and
ChooseFrames take the request, the stored syntax, and whether the pixels
were coded lossily:
req.Header.Set("Accept", `multipart/related; type="application/dicom"; transfer-syntax=1.2.840.10008.1.2.4.80`)
form, err := dicomweb.ChooseInstances(req, "1.2.840.10008.1.2.1", false)
fmt.Printf("%+v %v\n", form, err)
req.Header.Set("Accept", `multipart/related; type="application/dicom"; transfer-syntax=1.2.840.10008.1.2.4.50`)
_, err = dicomweb.ChooseInstances(req, "1.2.840.10008.1.2.1", false)
var refused *dicomweb.RequestError
if errors.As(err, &refused) {
fmt.Println(refused.Status(), refused)
}{Syntax:1.2.840.10008.1.2.4.80 Transcode:true Bare:false} <nil>
406 the instance is held in transfer syntax 1.2.840.10008.1.2.1 and cannot be sent in 1.2.840.10008.1.2.4.50: it is lossy, ...ParseRender and Render.Picture do the same for rendered pictures.
Writing a Backend
Backend
has four methods:
| Method | Does |
|---|---|
Query(ctx, identifier) | Answers a search as a C‑FIND would. The identifier carries Query/Retrieve Level (0008,0052): STUDY, SERIES or IMAGE. Results come in an order that does not change between calls, so paging works. |
Locate(ctx, study, series, instance) | Names the SOP Instance UIDs held of a study, a series or one instance. None, with no error, when nothing is held. |
Open(ctx, sopInstanceUID) | Returns the Part 10 file as held. The caller closes it. |
Put(ctx, instance) | Keeps an instance. An error refuses it with reason 0110H. |
This read-only Backend serves Part 10 files already on disk. It uses the
matching
package for queries:
// skipLevel leaves Query/Retrieve Level out of matching: no instance holds one.
var skipLevel = matching.Options{
Skip: func(parent tag.Tag, elem *dataelem.DataElement) bool {
t, _ := elem.Tag()
return parent == 0 && t == tag.New(0x0008, 0x0052)
},
}
type folder struct {
paths map[string]string // SOP Instance UID -> file
attrs map[string]*dataset.Dataset // SOP Instance UID -> its attributes
order []string
}
func (f *folder) Query(ctx context.Context, identifier *dataset.Dataset) ([]*dataset.Dataset, error) {
// A real archive answers each level once (one study, not one per
// instance); this sketch answers IMAGE level only.
if identifier.GetStringByKeyword("QueryRetrieveLevel") != "IMAGE" {
return nil, nil
}
id, err := matching.Compile(identifier, skipLevel)
if err != nil {
return nil, err
}
var answers []*dataset.Dataset
for _, uid := range f.order {
if id.MatchDataset(f.attrs[uid]) {
answer, err := matching.Response(identifier, f.attrs[uid], skipLevel)
if err != nil {
return nil, err
}
answers = append(answers, answer)
}
}
return answers, nil
}
func (f *folder) Locate(ctx context.Context, study, series, instance string) ([]string, error) {
var uids []string
for _, uid := range f.order {
ds := f.attrs[uid]
if ds.GetStringByKeyword("StudyInstanceUID") != study ||
(series != "" && ds.GetStringByKeyword("SeriesInstanceUID") != series) ||
(instance != "" && uid != instance) {
continue
}
uids = append(uids, uid)
}
return uids, nil
}
func (f *folder) Open(ctx context.Context, sopInstanceUID string) (io.ReadSeekCloser, error) {
return os.Open(f.paths[sopInstanceUID])
}
func (f *folder) Put(ctx context.Context, instance *dataset.Dataset) error {
return errors.New("this archive is read-only") // each instance refused, 0110H
}It is mounted the same way: mux.Handle("/files/", http.StripPrefix("/files", dicomweb.NewServer(files))). An instance search for Modality=MR found one
match. A retrieve returned the file. A store came back with one failed
instance and a *StatusError.
Important
Drop Query/Retrieve Level from matching, as skipLevel does above. No
stored instance holds that attribute, so without the skip nothing matches.
qrscp -web
qrscp serves its archive over DIMSE and, with -web, over DICOMweb at
/dicom-web:
$ go-dicom qrscp -port 41003 -output archive -web 41080
Starting DICOM Query/Retrieve SCP
AE Title: QRSCP
Port: 41003
Storage: archive
...
DICOMweb: http://127.0.0.1:41080/dicom-web
Listening for associations... (Ctrl+C to stop)
...
Web: GET /dicom-web/studies -> 200
Web: POST /dicom-web/studies -> 200Each request is logged by method, path and status. The query string is left out, since a search can carry a patient's name.
-web value | Listens on | Token |
|---|---|---|
41080 or :41080 | 127.0.0.1 only | optional |
localhost:41080, 127.0.0.1:41080 | that loopback address | optional |
0.0.0.0:41080, or any other host | that address | required |
$ go-dicom qrscp -port 41004 -output archive -web 0.0.0.0:41081
Error: -web 0.0.0.0:41081 can be reached from other machines, so it needs -web-token (or DICOMWEB_TOKEN): without one anybody who can reach the port can read the archiveWith a token, every request needs Authorization: Bearer <token>. Otherwise
the answer is 401. A path outside /dicom-web gets 404. Under -tls, the
service is HTTPS with the same certificate, and with -tls-ca it asks for a
client certificate. See TLS and security.
Tip
Set the token in DICOMWEB_TOKEN rather than with -web-token. Anyone
on the machine can read a command-line option in the process list.
Limits and gotchas
- No XML, no UPS-RS, no capabilities service. STOW with metadata and separate bulk data gets 415.
- Fuzzy matching is answered literally, with a
Warning: 299header.includefield=allreturns the default attributes. - A study or series rendered whole gets 501, as does an instance with no Pixel Data, and Float or Double Float images.
- STOW failure reasons are A900H and 0110H only. A900H means the instance
is not of the study in the path. 0110H means
Putfailed. A part that is not a DICOM file has no UID, so it shows only in the status. - A request past the store bound gets 413. Instances that arrived whole before that point are kept.
- CONFORMANCE.md §4.1 lists every supported form and how each was checked.
See also
- DICOMweb client
- Query/retrieve and worklist for
dcmstoreand the matching rules - TLS and security
dicomwebon pkg.go.dev